package com.haierp.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.haierp.dto.MultiDeliveryFormDTO;
import com.haierp.enums.OrderStatus;
import com.haierp.enums.ShippingOrderStatus;
import com.haierp.enums.ShippingOrderType;
import com.haierp.enums.StockUpStatus;
import com.haierp.exception.ErpCommonException;
import com.haierp.exception.InventoryException;
import com.haierp.mapper.ErpOrderMapper;
import com.haierp.mapper.InventoryAreaMapper;
import com.haierp.mapper.InventoryInoutMapper;
import com.haierp.mapper.InventoryRecordMapper;
import com.haierp.mapper.OuterOrderDetailMapper;
import com.haierp.mapper.ShippingOrderMapper;
import com.haierp.mapper.ShippingTrackMapper;
import com.haierp.model.ErpOrder;
import com.haierp.model.FileManage;
import com.haierp.model.Inventory;
import com.haierp.model.InventoryArea;
import com.haierp.model.InventoryInout;
import com.haierp.model.InventoryRecord;
import com.haierp.model.LogisticCompany;
import com.haierp.model.LogisticType;
import com.haierp.model.Seller;
import com.haierp.model.ShippingOrder;
import com.haierp.model.ShippingTrack;
import com.haierp.model.WxUser;
import com.haierp.model.sale.OuterOrder;
import com.haierp.model.sale.OuterOrderDetail;
import com.haierp.service.IErpOrderService;
import com.haierp.service.IFileManageService;
import com.haierp.service.IInventoryService;
import com.haierp.service.IItemService;
import com.haierp.service.IOuterOrderService;
import com.haierp.service.ISellerService;
import com.haierp.service.ISequenceUtilService;
import com.haierp.service.IShippingOrderService;
import com.haierp.service.IWarehouseService;
import com.haierp.service.IWxUserService;
import com.haierp.service.logistics.IFadRoadService;
import com.haierp.service.logistics.IHaiDaiBaoService;
import com.haierp.service.logistics.IHaihuService;
import com.haierp.service.logistics.IOneCangService;
import com.haierp.service.logistics.ISiFangService;
import com.haierp.service.logistics.IXloboService;
import com.haierp.service.logistics.IYoukeService;
import com.haierp.service.logistics.IYunTongService;
import com.haierp.util.AnalysisExcelUtil;
import com.haierp.util.DateUtil;
import com.haierp.util.JsonPageResult;
import com.haierp.util.JsonResult;
import com.haierp.util.MapUtil;
import com.haierp.util.Money;
import com.haierp.util.ExcelTool.ExcelHelper;
import com.haierp.vo.ShippingOrderQueryVO;
import com.haierp.vo.ShippingTrackVO;
import com.haierp.vo.json.PicModel;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.Barcode128;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.shiro.ShiroUser;
import com.wangzhixuan.commons.utils.HaiJsonUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/shippingOrder")
public class ShippingOrderController extends BaseController {
	
	@Autowired
	private IShippingOrderService shippingOrderService;
	@Autowired
	private ShippingOrderMapper shippingOrderMapper;
	@Autowired
	private IErpOrderService erpOrderService;
	
	@Autowired
	private IYoukeService youkeService;
	
	@Autowired
	private IYunTongService yunTongService;
	
	@Autowired
	private ShippingTrackMapper shippingTrackMapper;
	
	@Autowired
	private IHaihuService haihuService;
	@Autowired
	private IWxUserService wxUserService;
	
	@Autowired
	private IOuterOrderService outerOrderService;
	@Autowired
	private IItemService iItemService;
	@Autowired
	private ISellerService sellerService;
	@Autowired
	private ISiFangService siFangService;
	@Autowired
	private IFadRoadService fadRoadService;
	
	@Autowired
	private ErpOrderMapper erpOrderMapper;
	
	@Autowired
	private IFileManageService fileManageService;
	
	@Autowired
	private IHaiDaiBaoService haiDaiBaoService;
	
	@Autowired
	private IWarehouseService warehouseService;
	
	@Autowired
	private InventoryRecordMapper inventoryRecordMapper;
	
	@Autowired
	private InventoryAreaMapper inventoryAreaMapper;
	
	@Autowired
	private InventoryInoutMapper inventoryInoutMapper;
	
	@Autowired
	private IInventoryService inventoryService;
	
	@Autowired
	private OuterOrderDetailMapper outerOrderDetailMapper;
	
	@Autowired
	private IXloboService xloboService;
	
	@Autowired
	private IOneCangService oneCangService;
	
	@Autowired
	private ISequenceUtilService sequenceUtilService;


	//查询发货单列表
	@RequestMapping("/query")
	@ResponseBody
	public Object query(ShippingOrderQueryVO shippingOrderQueryVO) {
		JsonPageResult<List<ShippingOrder>> result = new JsonPageResult<>();
		if(shippingOrderQueryVO.getStartOrderTime() != null) {
			String startOrderTimeStr = DateUtil.ymdFormat(shippingOrderQueryVO.getStartOrderTime());
			Date startOrderTime = DateUtil.parseDate(startOrderTimeStr + " 00:00:00");
			shippingOrderQueryVO.setStartOrderTime(startOrderTime);
		}
		if(shippingOrderQueryVO.getEndOrderTime() != null) {
			String endOrderTimeStr = DateUtil.ymdFormat(shippingOrderQueryVO.getEndOrderTime());
			Date endOrderTime = DateUtil.parseDate(endOrderTimeStr + " 23:59:59");
			shippingOrderQueryVO.setEndOrderTime(endOrderTime);
		}
		if(shippingOrderQueryVO.getStartActionTime() != null) {
			String startActionTimeStr = DateUtil.ymdFormat(shippingOrderQueryVO.getStartActionTime());
			Date startActionTime = DateUtil.parseDate(startActionTimeStr + " 00:00:00");
			shippingOrderQueryVO.setStartActionTime(startActionTime);
		}
		if(shippingOrderQueryVO.getEndActionTime() != null) {
			String endActionTimeStr = DateUtil.ymdFormat(shippingOrderQueryVO.getEndActionTime());
			Date endActionTime = DateUtil.parseDate(endActionTimeStr + " 23:59:59");
			shippingOrderQueryVO.setEndActionTime(endActionTime);
		}
		//如果是代理
		ShiroUser shiroUser = this.getShiroUser();
		shippingOrderQueryVO.setCompanyId(shiroUser.getCompanyId());//所属公司
		Set<String> roles = shiroUser.getRoles();
		if(roles.contains("irhdaili")) {
			String[] logingNameArr = shiroUser.getLoginName().split("_");
			if(logingNameArr.length<2 || StringUtils.isBlank(logingNameArr[1])) {
				throw new ErpCommonException("用户权限异常");
			}
			shippingOrderQueryVO.setSalesId(Integer.parseInt(logingNameArr[1]));
			Seller seller = sellerService.selectById(shippingOrderQueryVO.getSalesId());
			if(seller.getOpenId()!=null) {
				shippingOrderQueryVO.setOpenId(seller.getOpenId());
			}
		}
		if(roles.contains("irhbuyer")) {
			shippingOrderQueryVO.setUserCreate(shiroUser.getLoginName());
		}

		result = shippingOrderService.queryShippingOrders(shippingOrderQueryVO);

		if(!roles.contains("telephone")) {
			List<ShippingOrder> shippingOrderList = result.getData();
			shippingOrderList.forEach(shippingOrder -> {
				String tel = shippingOrder.getTelephone();
				if(StringUtil.isNotBlank(tel)) {
					shippingOrder.setPerPhone(tel.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
				}
			});
		}

		if(roles.contains("irhdaili")) {
			result.setAgentRoler(true);
		}
		if(roles.contains("noexport")) {
			result.setNoEexportRoler(true);
		}
		if(roles.contains("packager")) {
			result.setPackager(true);
		}
		if(roles.contains("yunying") || roles.contains("admin")) {
			result.setYunyinger(true);
		}
		if(shiroUser.getCompanyId() == 2 || shiroUser.getCompanyId() == 3) {
			result.setXhsButton(true);
		}
		result.setSuccess(true);
		return result;
	}
	
	//合单发货表单
	@RequestMapping("/multiDeliveryForm")
	@ResponseBody
	public Object multiDeliveryForm(String erpOrderId) throws InventoryException {
		if(erpOrderId.equals("[]")) {
			throw new ErpCommonException("请选中可发货的子订单！");
		}
		JsonResult<MultiDeliveryFormDTO> result = new JsonResult<>();
		ShiroUser shiroUser = this.getShiroUser();
		boolean ifDoubleShoes = false;
		boolean ifcombination= false;
		boolean ifwineContains = false;
		boolean ifCostco = false;
		try {
			if(shiroUser.getCompanyId() == 1L){
				List<ErpOrder> ErpOrderPrice = shippingOrderService.queryShippingOrderDetail(erpOrderId);
				double priceTotall = 0.0;
				for (ErpOrder erpOrder : ErpOrderPrice) {
					priceTotall += erpOrder.getSalePrice() * erpOrder.getQuantity();
				}
				int shNum = 0;
				for (ErpOrder erpOrder : ErpOrderPrice) {
					 if(erpOrder.getCategoryName().equals("鞋靴")){
						 shNum++;
					 };
					 if(erpOrder.getCategoryName().equals("精品红酒")) {
						 ifwineContains = true;
					 };
					 if(erpOrder.getScale() != null && erpOrder.getScale().contains("2瓶/组")) {
						 ifcombination = true; 
					 }
					 if(!erpOrder.getBuySite().contains("Costco") && (erpOrder.getCategoryName().equals("男装") || erpOrder.getCategoryName().equals("女装") || erpOrder.getCategoryName().equals("潮流服饰"))) {
						 ifCostco = true;
					 }
				}
				if(ErpOrderPrice.size()==1 && ErpOrderPrice.get(0).getCategoryName().equals("鞋靴") && ErpOrderPrice.get(0).getQuantity()>1){
					ifDoubleShoes = true;
				}
				if(shNum>=2){ 
					ifDoubleShoes = true;
				}
			
				ShippingOrderQueryVO ykShipping = Money.getYeType(ErpOrderPrice);
				ShippingOrderQueryVO pxShipping = Money.getPxType(ErpOrderPrice);
				MultiDeliveryFormDTO putbackDto = shippingOrderService.queryByErpOrderId(erpOrderId);
				if(StringUtils.isBlank(putbackDto.getIdCard())) {
					for (ErpOrder erpOrder : ErpOrderPrice) {
						if(StringUtils.isBlank(erpOrder.getIdCard()) && StringUtils.isNotBlank(erpOrder.getTelephone())) {
							EntityWrapper<ShippingOrder> entityWrapper = new EntityWrapper<ShippingOrder>();
							entityWrapper.where("receiver={0} and telephone={1} and status=0 and id_card IS NOT NULL", erpOrder.getReceiver(), erpOrder.getTelephone());
							List<ShippingOrder> listOrders = shippingOrderService.selectList(entityWrapper);
							if(listOrders.size() > 0) {
								putbackDto.setIdCard(listOrders.get(0).getIdCard());
							}
						
						}
					}
				}
				if ((ykShipping.getFinallyFreight() < pxShipping.getFinallyFreight()) && StringUtils.isNotBlank(putbackDto.getIdCard()) && priceTotall<= 2000.00 && !shiroUser.getLoginName().equals("steph")) {
					putbackDto.setLogisticCompany("邮客");
					putbackDto.setType(ykShipping.getBestType());
					putbackDto.setFreight(ykShipping.getFinallyFreight());
				} 
				if((ykShipping.getFinallyFreight() > pxShipping.getFinallyFreight()) && StringUtils.isNotBlank(putbackDto.getIdCard())) {
					putbackDto.setLogisticCompany("4PX");
					putbackDto.setType(pxShipping.getBestType());
					putbackDto.setFreight(pxShipping.getFinallyFreight());
				}
				if (StringUtils.isBlank(putbackDto.getIdCard())) {
					boolean cline = false;
					Map<String, Object> categorymap = MapUtil.getCategoryUsac();
					for (ErpOrder erpOrder : ErpOrderPrice) {
						for (Map.Entry<String, Object> entry : categorymap.entrySet()) {
							if (!erpOrder.getItemName().contains("皮带")
									&& erpOrder.getCategoryName().equals(entry.getKey())) {
								cline = true;
							}
						}
					}
					putbackDto.setLogisticCompany("运通快递");
					if (cline) {
						putbackDto.setType(5);
					} else {
						putbackDto.setType(4);

					}
				}
				
				if(putbackDto.getLogisticCompany().equals("邮客") && putbackDto.getType() == 10 && ifCostco){
					putbackDto.setLogisticCompany("4PX");
					putbackDto.setType(pxShipping.getBestType());
					putbackDto.setFreight(pxShipping.getFinallyFreight());
				}
				/*else {
					putbackDto.setLogisticCompany("4PX");
					putbackDto.setType(pxShipping.getBestType());
					putbackDto.setFreight(pxShipping.getFinallyFreight());
				} else {
					putbackDto.setLogisticCompany("4PX");
					putbackDto.setType(8);
					putbackDto.setFreight(pxShipping.getFinallyFreight());
				}*/
				//香水线路匹配
				if(ErpOrderPrice.size() == 1 && ErpOrderPrice.get(0).getCategoryName().equals("潮流香水")) {
					putbackDto.setLogisticCompany("运通快递");
					putbackDto.setType(5);
				}
				//paike匹配
				if(ErpOrderPrice.size() == 1 && ErpOrderPrice.get(0).getItemCode().equals("I0301001Q66848") && StringUtils.isNotBlank(ErpOrderPrice.get(0).getIdCard())) {
					putbackDto.setLogisticCompany("邮客");
					if(ErpOrderPrice.get(0).getQuantity() > 1) {
						putbackDto.setType(1);
					} else {
						putbackDto.setType(10);
					}
				}
				//红酒线
				if(ifwineContains) {
					putbackDto.setLogisticCompany("4PX");
					putbackDto.setType(18);
				}
				result.setData(putbackDto);
				if(StringUtils.isNotBlank(putbackDto.getIdCard())) {
					EntityWrapper<ShippingOrder> entityWrapper = new EntityWrapper<ShippingOrder>();
					entityWrapper.where("id_card={0} and logistic_company={1} and gmt_create>=DATE_SUB(CURDATE(), INTERVAL 6 DAY)", putbackDto.getIdCard(), putbackDto.getLogisticCompany());
					int num = shippingOrderService.selectCount(entityWrapper);
					if(num >= 2 && putbackDto.getLogisticCompany().equals("邮客")) {
						result.setData(putbackDto);
						return result.buildMsg("注意：此收件人已用\"" + putbackDto.getLogisticCompany() + "\"在一周之内发过2次以上请更换其他物流公司了").buildIsSuccess(true);
					} else if(num >= 5 && putbackDto.getLogisticCompany().equals("4PX")) {
						result.setData(putbackDto);
						return result.buildMsg("注意：此收件人已用\"" + putbackDto.getLogisticCompany() + "\"在一周之内发过5次以上请更换其他物流公司了").buildIsSuccess(true);
					} else if(ifcombination) {
						result.setData(putbackDto);
						return result.buildMsg("注意：此包裹包含组合商品,请打包注意！").buildIsSuccess(true);
					} else {
						result.setData(putbackDto);
						result.buildIsSuccess(true);
						return result;
					}
				}

			} else {
				result.setData(shippingOrderService.queryByErpOrderId(erpOrderId));
			}

			/*Set<String> roles = shiroUser.getRoles();
			if(!roles.contains("telephone")) {
				MultiDeliveryFormDTO multiDeliveryFormDTO = result.getData();
				String tel = multiDeliveryFormDTO.getTelephone();
				if(StringUtil.isNotBlank(tel)) {
					multiDeliveryFormDTO.setTelephone(tel.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
				}
			}*/

			result.buildIsSuccess(true);
		} catch(ErpCommonException e) {
			result.buildMsg(e.getErrorMsg()).buildIsSuccess(false);
		}
		return result;
	}
	
	//合单发货(将多个子订单合并成一个包裹)
	@RequestMapping("/multiDelivery")
	@ResponseBody
	public Object multiDelivery(ShippingOrder shippingOrder) throws InventoryException {
		JsonResult<String> result = new JsonResult<>();
		ShiroUser one = this.getShiroUser();
		String message = "";
		if(StringUtils.isNotBlank(shippingOrder.getErpOrderId())) {
			ShiroUser shiroUser = this.getShiroUser();
			shippingOrder.setUserCreate(shiroUser.getLoginName());
			shippingOrder.setCompanyId(shiroUser.getCompanyId());//所属公司
			shippingOrder.setLogisticType(shippingOrder.getShippingType()); //发货方式
			List<ErpOrder> erpOrderList = shippingOrderService.queryShippingOrderDetail(shippingOrder.getErpOrderId());
			if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海狐")) {
				if(erpOrderList.size()>1) {
					throw new ErpCommonException("海狐的包裹只能包含一个商品且数量为1，请选择其他物流公司！");
				}
				if(erpOrderList.get(0).getQuantity() > 1) {
					throw new ErpCommonException("海狐的包裹只能包含一个商品且数量为1，请选择其他物流公司！");
				}
				if(StringUtils.isEmpty(erpOrderList.get(0).getIdCard())) {
					throw new ErpCommonException("海狐物流发货单号缺少身份证信息");
				}
			}
			if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("邮客")) {
				if(shippingOrder.getReceiver().contains("小姐") || shippingOrder.getReceiver().contains("先生") || shippingOrder.getReceiver().contains("女士")) {
					throw new ErpCommonException("邮客预报姓名不规范,请规范收件人");
				}
			}
			//4PX C线校验
			if (shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("4PX")) {
				if (shippingOrder.getType() == 13) {
					int totallyFaxNum = 0; //总数限定20件
					double totallyFaxWei =shippingOrder.getWeightOut(); //总磅数11磅
					int clothNum = 0;//衣服总件数
					int shoesNum = 0;//鞋靴总件数
					int bagsNum = 0;//箱包总件数
					double cosmeticsWei = 0.0; //配饰类限制总磅数
					double jewelryWei = 0.0; //首饰类限制总磅数
					
					for (ErpOrder erpOrder : erpOrderList) {
						totallyFaxNum += erpOrder.getQuantity();
						//totallyFaxWei += erpOrder.getWeight();
						if(erpOrder.getCategoryName().equals("男装") || erpOrder.getCategoryName().equals("女装") || erpOrder.getCategoryName().equals("潮流服饰")) {
							clothNum += erpOrder.getQuantity();
						}
						if(erpOrder.getCategoryName().equals("潮流女包") || erpOrder.getCategoryName().equals("时尚男包") || erpOrder.getCategoryName().equals("精品钱包") || erpOrder.getCategoryName().equals("箱包皮具")) {
							bagsNum += erpOrder.getQuantity();
						}
						if(erpOrder.getCategoryName().equals("鞋靴")) {
							shoesNum += erpOrder.getQuantity();
						}
						if(erpOrder.getCategoryName().equals("配饰")) {
							cosmeticsWei += erpOrder.getWeight();
						}
						if(erpOrder.getCategoryName().equals("流行饰品")) {
							jewelryWei += erpOrder.getWeight();
						}
					}
					if(totallyFaxNum > 20 || totallyFaxWei >9.00) {
						throw new ErpCommonException("超过C线包裹限制总件数20或总磅数9磅");
					}
					if(clothNum>10){
						throw new ErpCommonException("衣服类超过C线服装上限10件");
					}
					if(shoesNum>3){
						throw new ErpCommonException("鞋靴超过C线上限3双");
					}
					if(bagsNum>2){
						throw new ErpCommonException("包包类超过C线上限2件");
					}
					if(cosmeticsWei>0.0 && totallyFaxWei>3.00){
						throw new ErpCommonException("配饰类超过C线上限3磅");
					}
					if(jewelryWei>0.0 && totallyFaxWei>3.00){
						throw new ErpCommonException("首饰类超过C线上限3磅");
					}
				} else {
					String completeAddress = shippingOrder.getReceiverState()+shippingOrder.getReceiverCity()+shippingOrder.getReceiverDistrict()+shippingOrder.getAddressDetail();
					Map<String, String> addressmap = MapUtil.getNoshippingAddress();
					for (Map.Entry<String, String> entry : addressmap.entrySet()) {
						if (completeAddress.equals(entry.getKey())) {
							throw new ErpCommonException("该地址本年度预报4PX总金额已超过贰万元整，请更换地址或物流公司！");
						}
					}
					
					double totallyPrince = 0.0;
					for (ErpOrder erpOrder : erpOrderList) {
						totallyPrince += erpOrder.getSalePrice();
					}
					if(totallyPrince > 1000) {
						throw new ErpCommonException("该包裹总价值已经超过4px上限, 请考虑修改子订单价格或者更换物流公司再发走！");   
					}
					/*if(erpOrderList.size() == 1 && erpOrderList.get(0).getQuantity()> 1 && (erpOrderList.get(0).getSalePrice() * erpOrderList.get(0).getQuantity() > 1000) ) {
						throw new ErpCommonException("该包裹内件可分割并且已经超过4px上限, 请考虑修改子订单价格或者拆单后再发走！");   
					}
					
					if(erpOrderList.size() > 1 && totallyPrince> 1000) {
						throw new ErpCommonException("该包裹内件可分割并且已经超过4px上限, 请考虑修改子订单价格或者拆单后再发走！"); 
					}*/
					if(StringUtil.isBlank(shippingOrder.getIdCard())) {
						throw new ErpCommonException("4PX不能发送身份证为空的包裹"); 
					}
				}
				
			}
			
			//运通校验
			if (shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("运通快递")){
				boolean cline = false;
				boolean pline = false;
                if (shippingOrder.getType() == 5) {
					Map<String, Object> categorymap = MapUtil.getCategoryUsap();
					for (ErpOrder erpOrder : erpOrderList) {
						for (Map.Entry<String, Object> entry : categorymap.entrySet()) {
							if (erpOrder.getCategoryName().equals(entry.getKey())) {
								cline = true;
							}
						}
					}
				}
                if (shippingOrder.getType() == 4) {
					Map<String, Object> categorymap = MapUtil.getCategoryUsac();
					for (ErpOrder erpOrder : erpOrderList) {
						for (Map.Entry<String, Object> entry : categorymap.entrySet()) {
							if (!erpOrder.getItemName().contains("皮带") && erpOrder.getCategoryName().equals(entry.getKey())) {
								pline = true;
							}
						}
					}
				}
				/*if(cline) {
					return result.buildMsg("注意：运通USA-C线路掺杂有不合规格的类目商品，请检查！").buildIsSuccess(true);
				}*/
				if(pline) {
					return result.buildMsg("注意：运通USA-P线路掺杂有不合规格的类目商品，请检查！").buildIsSuccess(true);
				}
			}
			//邮客食品校验
			if (shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("邮客") && shippingOrder.getType() == 6){
				for (ErpOrder erpOrder : erpOrderList) {
					if (erpOrder.getPurchasePrice() == null || erpOrder.getPurchasePrice() <= 1.00) {
						throw new ErpCommonException("食品线采购价格有误请给采购人员核对此采购价 SKUCODE:" + erpOrder.getSkuCode());
					}
				}
                  //软包装校验
				/*if (erpOrderList.size() == 1) {
					boolean specially = false;
					Map<String, String> categorymap = MapUtil.getCategoryNoFda();
					String category = erpOrderList.get(0).getCategoryName();
					for (Map.Entry<String, String> entry : categorymap.entrySet()) {
						if (category.equals(entry.getKey())) {
							specially = true;
						}
					}
					if (specially && !erpOrderList.get(0).getItemName().contains("内裤") && !erpOrderList.get(0).getItemName().contains("内衣") && !erpOrderList.get(0).getItemCode().equals("I0403001Q12440")) {
						throw new ErpCommonException("食品线不能发除内裤以外的软包装衣物");
					}

				}*/
			}
			//红酒线校验
			if (shippingOrder.getLogisticCompany() != null && shippingOrder.getLogisticCompany().equals("4PX") && shippingOrder.getType() == 18) {
				int wineNu = 0;
				for (ErpOrder erpOrder : erpOrderList) {
					wineNu += erpOrder.getQuantity();
					if (erpOrder.getPurchasePrice() == null || erpOrder.getPurchasePrice() < 12.00 || erpOrder.getPurchasePrice() > 20.00) {
						throw new ErpCommonException("红酒线该商品采购价格异常,请核对后发货： SKUCODE:" + erpOrder.getSkuCode());
					}
				}
				if (wineNu >= 6) {
					throw new ErpCommonException("超出红酒线的上限数量6个,请调整发货");
				}
			}
			//海带宝校验
			if (shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海带宝")) { 
				if(StringUtils.isBlank(shippingOrder.getIdCard()) || shippingOrder.getIdCard() == null) {
					throw new ErpCommonException("海带宝身份证信息不能为空！请调整发货");
				}
			}
			try {
				Set<Long> mainIds=shippingOrderService.multiDelivery(shippingOrder,one.getCompanyId());
				//更新主订单发货状态
				if(CollectionUtils.isNotEmpty(mainIds)){
					shippingOrderService.updateOuterstatus(mainIds);
				}
				//对接邮客
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("邮客")) {
					youkeService.createOrder(shippingOrder.getId());
				}
				//对接运通快递
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("运通快递")) {
					yunTongService.createOrder(shippingOrder.getId());
				}
				//对接海狐
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海狐")) {
					haihuService.createOrder(shippingOrder.getId());
				}
				//对接海狐联邦转运
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海狐联邦转运")) {
					haihuService.returnPackageNo(shippingOrder.getId());
					
				}
				//对接美国转运四方
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("4PX")) {
					message = siFangService.createOrder(shippingOrder.getId(),one.getCompanyId());
				}
				//对接联邦
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("联邦转运")) {
					fadRoadService.createOrder(shippingOrder.getId());
				}
				//对接海带宝
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海带宝")) {
					haiDaiBaoService.createOrder(shippingOrder.getId(),one.getCompanyId());
				}
				//对接贝海物流
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("贝海国际物流")) {
					message = xloboService.createOrder(shippingOrder.getId(),one.getCompanyId());
				}
				//对接1号仓
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海淘一号仓")) {
					message = oneCangService.createOrder(shippingOrder.getId());
				}
				//直接选择顺丰或者韵达快递补全status = 4特殊国内物流轨迹
				if(shippingOrder.getLogisticCompany()!=null && (shippingOrder.getLogisticCompany().equals("顺丰")|| shippingOrder.getLogisticCompany().equals("韵达") || shippingOrder.getLogisticCompany().equals("4PX澳洲"))) {
					ShippingTrack shippingTrack = new ShippingTrack();
					shippingTrack.setGmtCreate(new Date());
					shippingTrack.setGmtModify(new Date());
					shippingTrack.setStatus(4);
					shippingTrack.setLogisticNo(shippingOrder.getLogisticNo());
					shippingTrack.setInlandExpressId(shippingOrder.getLogisticCompany());
					shippingTrack.setInlandExpressNo(shippingOrder.getLogisticNo());
					shippingTrack.setShippingNo(shippingOrder.getShippingNo());
					shippingTrackMapper.insert(shippingTrack);
				}
				if(StringUtils.isBlank(message)){
					result.buildIsSuccess(true);
				} else {
					result.buildMsg(message).buildIsSuccess(false);
				}
			} catch(ErpCommonException e) {
				result.buildMsg(e.getErrorMsg()).buildIsSuccess(false);
			}
		} else {
			result.buildMsg("错误数据").buildIsSuccess(false);
		}
		return result;
	}
	
	//批量发货表单(检查是否有需要合单发货的，检查是否有需要等待一起合单发货的)
	@RequestMapping("/batchDeliveryForm")
	@ResponseBody
	public Object batchDeliveryForm(String erpOrderId) {
		JsonResult<String> result = new JsonResult<>();
		ShiroUser one = this.getShiroUser();
		try {
			String s = erpOrderId.replace("&quot;", "\"");
			List<Long> erpOrderIdList = HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
			List<ErpOrder> erpOrderList = erpOrderService.selectBatchIds(erpOrderIdList);
			
			StringBuffer erpNoErrStr = new StringBuffer();
			StringBuffer erpNoTipStr = new StringBuffer();
			for(ErpOrder erpOrder : erpOrderList) {
				OuterOrder orderone = outerOrderService.selectById(erpOrder.getOuterOrderId());
				if( orderone.getStatus() == null || orderone.getStatus() == -3) {
					throw new ErpCommonException("主订单未付款或订单状态不对，主订单号：" + orderone.getOrderNo());
				}
				if (erpOrder.getStockStatus() == null || erpOrder.getStockStatus() != StockUpStatus.STOCKUP.getCode()) {
					throw new ErpCommonException("商品备货状态不对，子订单号：" + erpOrder.getErpNo());
				}
				if (StringUtils.isBlank(erpOrder.getReceiver()) || StringUtils.isBlank(erpOrder.getTelephone())
						|| StringUtils.isBlank(erpOrder.getReceiverState())
						|| StringUtils.isBlank(erpOrder.getReceiverCity())
						|| StringUtils.isBlank(erpOrder.getReceiverDistrict())) {
					throw new ErpCommonException("收货人地址不能为空：" + erpOrder.getErpNo());
				}
				ErpOrder tjErpOrder = new ErpOrder();
				tjErpOrder.setReceiver(erpOrder.getReceiver());
				tjErpOrder.setCompanyId(one.getCompanyId());//所属公司
				tjErpOrder.setTelephone(erpOrder.getTelephone());
				tjErpOrder.setReceiverState(erpOrder.getReceiverState());
				tjErpOrder.setReceiverCity(erpOrder.getReceiverCity());
				tjErpOrder.setReceiverDistrict(erpOrder.getReceiverDistrict());
				tjErpOrder.setStatus(0);								//订单状态：新建
				//tjErpOrder.setStockStatus(erpOrder.getStockStatus());	//备货状态：已备货
				//tjErpOrder.setWarehouseId(erpOrder.getWarehouseId());	//相同仓库
				
				
				EntityWrapper<ErpOrder>  entityWrapper = new EntityWrapper<ErpOrder>();
				entityWrapper.setEntity(tjErpOrder);
				List<ErpOrder> selErpOrderList = erpOrderService.selectList(entityWrapper);
				int countErr = 0;
				int countTip = 0;
				for(int i=0; i<selErpOrderList.size(); i++) {
					ErpOrder selErpOrder= selErpOrderList.get(i);
					//不在同一仓库的情况，不用考虑
					if(selErpOrder.getWarehouseId()!=null && selErpOrder.getWarehouseId()!=erpOrder.getWarehouseId()) continue;
					//在同一个仓库，已备货
					if(selErpOrder.getStockStatus()==StockUpStatus.STOCKUP.getCode()) {
						countErr++;
					} else {	//备货未完成，这个时候仓库ID不一定有值
						countTip++;
					}
				}
				if(countErr > 1) {
					erpNoErrStr.append("\r\n" + erpOrder.getErpNo() + ";");
				}
				if(countTip > 0) {
					erpNoTipStr.append(erpOrder.getErpNo() + "；");
				}
			}
			
			if(!erpNoErrStr.toString().equals("")) {
				result.buildIsSuccess(false).buildMsg("需要合单发货的子订单：" + erpNoErrStr.toString());
			} else if(!erpNoTipStr.toString().equals("")) {
				result.buildIsSuccess(true).buildData("需要等待合单发货的子订单：" + erpNoTipStr.toString());
			} else {
				result.buildIsSuccess(true);
			}
		} catch(ErpCommonException e) {
			result.buildMsg(e.getErrorMsg()).buildIsSuccess(false);
		}
		return result;
	}
	
	//批量发货(每个子订单作为一个包裹)
	@RequestMapping("/batchDelivery")
	@ResponseBody
	public Object batchDelivery(ShippingOrder shippingOrder) throws InventoryException {
		JsonResult<String> result = new JsonResult<>();
		ShiroUser one = this.getShiroUser();
		shippingOrder.setLoginName(one.getLoginName());
		shippingOrder.setLogisticType(0);//批量发货没有拼邮
		String message = "";
		if(StringUtils.isNotBlank(shippingOrder.getErpOrderId())) {
			ShiroUser shiroUser = this.getShiroUser();
			shippingOrder.setUserCreate(shiroUser.getLoginName());
			shippingOrder.setCompanyId(shiroUser.getCompanyId());
			if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海狐")){
				List<ErpOrder> ErpOrderList = shippingOrderService.queryShippingOrderDetail(shippingOrder.getErpOrderId());
				if(ErpOrderList.size()>1){
					throw new ErpCommonException("海狐的包裹只能包含一个商品且数量为1，请选择其他物流公司！");
				}
				if(ErpOrderList.get(0).getQuantity() > 1) {
					throw new ErpCommonException("海狐的包裹只能包含一个商品且数量为1，请选择其他物流公司！");
				}
				if(StringUtils.isEmpty(ErpOrderList.get(0).getIdCard())){
					throw new ErpCommonException("海狐物流发货单号缺少身份证信息");
				}
			}
			try {
				Map<String, Set<Long>> idsMap = shippingOrderService.batchDelivery(shippingOrder);
				Set<Long> mainIds = idsMap.get("mainIds");
				//更新主订单发货状态
				if(CollectionUtils.isNotEmpty(mainIds)){
					shippingOrderService.updateOuterstatus(mainIds);
				}
				Set<Long> shippingOrderIds = idsMap.get("shippingOrderIds");
				//对接邮客
				if(CollectionUtils.isNotEmpty(shippingOrderIds) && shippingOrder.getLogisticCompany().equals("邮客")) {
					for(Long shippingOrderId : shippingOrderIds) {
						youkeService.createOrder(shippingOrderId);
					}
				}
				//对接运通快递
				if(CollectionUtils.isNotEmpty(shippingOrderIds) && shippingOrder.getLogisticCompany().equals("运通快递")) {
					for(Long shippingOrderId : shippingOrderIds) {
						yunTongService.createOrder(shippingOrderId);
					}
				}
				//对接海狐
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海狐")) {
					for(Long shippingOrderId : shippingOrderIds) {
						haihuService.createOrder(shippingOrderId);
					}
					
				}
				//对接海狐联邦转运
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海狐联邦转运")) {
					    for(Long shippingOrderId : shippingOrderIds) {
					    	   haihuService.returnPackageNo(shippingOrderId);
						}
				}
				//对接美国转运四方
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("4PX")) {
					for(Long shippingOrderId : shippingOrderIds) {
						message = siFangService.createOrder(shippingOrderId,one.getCompanyId());
					}
				}
				//对接联邦
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("联邦转运")) {
					for(Long shippingOrderId : shippingOrderIds) {
						fadRoadService.createOrder(shippingOrderId);
					}
				}
				//对接海带宝
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海带宝")) {
					for(Long shippingOrderId : shippingOrderIds) {
						haiDaiBaoService.createOrder(shippingOrderId,one.getCompanyId());
					}
				}
				//对接贝海物流
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("贝海国际物流")) {
					for(Long shippingOrderId : shippingOrderIds) {
						message = xloboService.createOrder(shippingOrderId,one.getCompanyId());
					}
				}
				//对接一号仓
				if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海淘一号仓")) {
					for(Long shippingOrderId : shippingOrderIds) {
						message = oneCangService.createOrder(shippingOrderId);
					}
				}
				//直接选择顺丰或者韵达快递补全status = 4特殊国内物流轨迹
				if(shippingOrder.getLogisticCompany()!=null && (shippingOrder.getLogisticCompany().equals("顺丰")|| shippingOrder.getLogisticCompany().equals("韵达") || shippingOrder.getLogisticCompany().equals("4PX澳洲"))) {
					ShippingTrack shippingTrack = new ShippingTrack();
					shippingTrack.setGmtCreate(new Date());
					shippingTrack.setGmtModify(new Date());
					shippingTrack.setStatus(4);
					shippingTrack.setLogisticNo(shippingOrder.getLogisticNo());
					shippingTrack.setInlandExpressId(shippingOrder.getLogisticCompany());
					shippingTrack.setInlandExpressNo(shippingOrder.getLogisticNo());
					shippingTrack.setShippingNo(shippingOrder.getShippingNo());
					shippingTrackMapper.insert(shippingTrack);
				}
				if(StringUtils.isBlank(message)) {
					result.buildIsSuccess(true);
				} else {
					result.buildMsg(message).buildIsSuccess(false);
				}
			} catch(ErpCommonException e) {
				result.buildMsg(e.getErrorMsg()).buildIsSuccess(false);
			}
		} else {
			result.buildMsg("错误数据").buildIsSuccess(false);
		}
		return result;
	}

	//修改发货单
	@RequestMapping("/update")
	@ResponseBody
	public Object update(ShippingOrder shippingOrder) {
		JsonResult<String> result = new JsonResult<>();
		ShiroUser shiroUser = this.getShiroUser();
		shippingOrder.setUserCreate(shiroUser.getLoginName());
		if(shippingOrder.getId() != null) {
			String message = null;
			if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("运通快递") && StringUtil.isBlank(shippingOrder.getLogisticNo())){
				shippingOrder.setShippingNo("YTPDX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)+sequenceUtilService.gainPKGSequence());
			} else if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("4PX") && StringUtil.isBlank(shippingOrder.getLogisticNo())){
				shippingOrder.setShippingNo("4PXPDX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)+sequenceUtilService.gainPKGSequence());
			} else if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("邮客") && StringUtil.isBlank(shippingOrder.getLogisticNo())){
				shippingOrder.setShippingNo("YKPDX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)+sequenceUtilService.gainPKGSequence());
			} else if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海带宝") && StringUtil.isBlank(shippingOrder.getLogisticNo())){
				shippingOrder.setShippingNo("HDBPDX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainPKGSequence());
			} else if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海淘一号仓") && StringUtil.isBlank(shippingOrder.getLogisticNo())){
				shippingOrder.setShippingNo("HTPDX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)+sequenceUtilService.gainPKGSequence());
			}
			shippingOrderService.update(shippingOrder);
			if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("邮客") && StringUtil.isBlank(shippingOrder.getLogisticNo())) {	//对接邮客
			     if(shippingOrder.getReceiver().contains("小姐") || shippingOrder.getReceiver().contains("先生") || shippingOrder.getReceiver().contains("女士")) {
						throw new ErpCommonException("邮客预报姓名不规范,请规范收件人");
					} else {
						youkeService.createOrder(shippingOrder.getId());
					}
			} else if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("运通快递") && StringUtil.isBlank(shippingOrder.getLogisticNo())) {//对接运通
				yunTongService.createOrder(shippingOrder.getId());
			} else if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("4PX") && StringUtil.isBlank(shippingOrder.getLogisticNo())) {//对接4PX
				message = siFangService.createOrder(shippingOrder.getId(),shiroUser.getCompanyId());
			} else if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海狐联邦转运") && StringUtil.isBlank(shippingOrder.getLogisticNo())) {//对接海狐联邦转运
				haihuService.returnPackageNo(shippingOrder.getId());
			} else if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("联邦转运") && StringUtil.isBlank(shippingOrder.getLogisticNo())) {//对接联邦
				fadRoadService.createOrder(shippingOrder.getId());
			} else if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海带宝") && StringUtil.isBlank(shippingOrder.getLogisticNo())) {//对接海带宝
				haiDaiBaoService.createOrder(shippingOrder.getId(),shiroUser.getCompanyId());
			} else if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("贝海国际物流") && StringUtil.isBlank(shippingOrder.getLogisticNo())){
				xloboService.createOrder(shippingOrder.getId(),shiroUser.getCompanyId());
			} else if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海淘一号仓") && StringUtil.isBlank(shippingOrder.getLogisticNo())) {
				message = oneCangService.createOrder(shippingOrder.getId());
			}
			else if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海狐") && StringUtil.isBlank(shippingOrder.getLogisticNo())) {//对接海狐
				List<ErpOrder> ErpOrderList = shippingOrderService.queryShippingOrderDetail(shippingOrder.getErpOrderId());
				if(ErpOrderList.size()>1) {
					throw new ErpCommonException("海狐的包裹只能包含一个商品且数量为1，请选择其他物流公司！");
				}else if(ErpOrderList.get(0).getQuantity() > 1) {
					throw new ErpCommonException("海狐的包裹只能包含一个商品且数量为1，请选择其他物流公司！");
				}else if(StringUtils.isEmpty(ErpOrderList.get(0).getIdCard())){
					throw new ErpCommonException("海狐物流发货单号缺少身份证信息");
				}else{
					haihuService.createOrder(shippingOrder.getId());
				}
			} else if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海狐联邦转运") && StringUtil.isBlank(shippingOrder.getLogisticNo())){
				haihuService.returnPackageNo(shippingOrder.getId());
			}
			else if(shippingOrder.getLogisticCompany()!=null && (shippingOrder.getLogisticCompany().equals("顺丰")|| shippingOrder.getLogisticCompany().equals("韵达"))){
				ShippingTrack shippingTrack = new ShippingTrack();
				shippingTrack.setGmtCreate(new Date());
				shippingTrack.setGmtModify(new Date());
				shippingTrack.setStatus(4);
				shippingTrack.setLogisticNo(shippingOrder.getLogisticNo());
				shippingTrack.setInlandExpressId(shippingOrder.getLogisticCompany());
				shippingTrack.setInlandExpressNo(shippingOrder.getLogisticNo());
				shippingTrack.setShippingNo(shippingOrder.getShippingNo());
				shippingTrackMapper.insert(shippingTrack);
			}
			if(StringUtil.isBlank(message)) {
				result.setSuccess(true);
			} else {
				result.buildMsg(message).buildIsSuccess(false);
			}
		} else {
			result.buildMsg("错误数据").buildIsSuccess(false);
		}
		return result;
	}
	
	//查询物流公司
	@RequestMapping("/queryLogisticCompany")
	@ResponseBody
	public Object queryLogisticCompany() {
		JsonResult<List<LogisticCompany>> result = new JsonResult<>();
		List<LogisticCompany> LogisticCompanyList = shippingOrderService.queryLogisticCompany();
		result.setData(LogisticCompanyList);
		result.setSuccess(true);
		return result;
	}
	//查询小程序代理角色
	@RequestMapping("/queryAgentMan")
	@ResponseBody
	public Object queryAgentMan() {
		JsonResult<List<WxUser>> result = new JsonResult<>();
		EntityWrapper<WxUser> selEntityWrapper = new EntityWrapper<WxUser>();
		selEntityWrapper.where("role=1");
		List<WxUser> wxUserList = wxUserService.selectList(selEntityWrapper);
		result.setData(wxUserList);
		result.setSuccess(true);
		return result;
	}
	//包裹号标签导出
	@RequestMapping("/shippingOrderExportPdf")
	@ResponseBody
	public ResponseEntity<byte[]> shippingOrderExportPdf(String shippingOrderIds) throws Exception {
		if(StringUtil.isBlank(shippingOrderIds) || shippingOrderIds.equals("[]")) return null;
		ShiroUser shiroUser = this.getShiroUser();
		Set<String> roles = shiroUser.getRoles();
		String userPrinter = shiroUser.getLoginName();

		ByteArrayOutputStream  out = new ByteArrayOutputStream();
		//PDF设置
    	Rectangle rect = new Rectangle(315, 256);
    	Document document = new Document(rect, 0, 0, 0, 0);
		//PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
		PdfWriter writer = PdfWriter.getInstance(document, out);
		BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);	
		Font FontChinese_15 = new Font(bfChinese, 15, Font.NORMAL);
		Font FontChinese_10 = new Font(bfChinese, 10, Font.NORMAL);
		Font FontChinese_18 = new Font(bfChinese, 18, Font.NORMAL);
		Font FontChinese_36 = new Font(bfChinese, 30, Font.NORMAL);
		Font FontEnglish_8 = FontFactory.getFont(FontFactory.COURIER, 8);
		document.open();
		PdfContentByte cd = writer.getDirectContent();
		// =========虚线start===================
		CustomDashedLineSeparator separator = new CustomDashedLineSeparator();
		separator.setDash(1);
		separator.setGap(1);
		separator.setLineWidth(0.5f);
		separator.setPercentage(100f);
		separator.setOffset(2);
		Chunk linebreak = new Chunk(separator);
		Paragraph lineParagraph = new Paragraph();
		lineParagraph.add(linebreak);
		lineParagraph.setLeading(12);
		lineParagraph.setSpacingBefore(0);
		lineParagraph.setSpacingAfter(2);
		// =========虚线end===================
		float[] tableWidths = {0.65f, 0.27f, 0.08f};
		
		String s = shippingOrderIds.replace("&quot;", "\"");
		List<Long> shippingOrderIdList = HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
		List<ShippingOrder> shippingOrderList = shippingOrderService.selectBatchIds(shippingOrderIdList);
		
		int shippingOrderListLength = shippingOrderList.size();
		for(int i=0; i<shippingOrderListLength; i++) {
			boolean ifcombination= false;
			boolean ifneedpackage= false;
			ShippingOrder shippingOrder = shippingOrderList.get(i);
			String erpOrderId = shippingOrder.getErpOrderId();
			String shoppingDetail = "";
			/*String ss = erpOrderId.replace("&quot;", "\"");
			List<Long> erpOrderIdList = HaiJsonUtils.toBean(ss, new TypeReference<List<Long>>(){});
			List<ErpOrder> erpOrderList = erpOrderService.selectBatchIds(erpOrderIdList);*/
			List<ErpOrder> erpOrderList = shippingOrderService.queryShippingOrderDetail(erpOrderId);
			Map<String, Integer> param = new HashMap<String, Integer>();
			if(erpOrderList.size()>0){
				Map<Long, String> warehouseMap = warehouseService.getWarehouseMap();
				Map<String, String> categorymap = MapUtil.getWareHouse();
				if(StringUtils.isNotBlank(categorymap.get(warehouseMap.get(erpOrderList.get(0).getWarehouseId())))) {
					shippingOrder.setWarehouseName(categorymap.get(warehouseMap.get(erpOrderList.get(0).getWarehouseId())));
				} else {
					shippingOrder.setWarehouseName(warehouseMap.get(erpOrderList.get(0).getWarehouseId()));
				}
				for (ErpOrder erpOrder : erpOrderList) {
					 if(erpOrder.getScale() != null && (erpOrder.getScale().contains("2瓶/组") || erpOrder.getScale().contains("2瓶1组"))) {
						 ifcombination = true; 
					 }
				}
				//纯衣物打包字样判别
				for (ErpOrder erpOrder : erpOrderList) {
					Map<String, Object> categorymapcloth = MapUtil.getClothes();
					for (Map.Entry<String, Object> entry : categorymapcloth.entrySet()) {
						if (erpOrder.getCategoryName().equals(entry.getKey())) {
							ifneedpackage = true;
						}
					}
					param.put(erpOrder.getCategoryName(), param.getOrDefault(erpOrder.getCategoryName(), 0) + erpOrder.getQuantity());
					
				}
			}
			
			for (Map.Entry<String, Integer> entry : param.entrySet()) {
				shoppingDetail += entry.getKey() + "*" + entry.getValue().toString();
			}
			
			if(StringUtil.isBlank(shippingOrder.getLogisticNo())) {
				continue;
			}
			//打印者
			if(StringUtil.isBlank(shippingOrder.getUserPrinter())) {
				shippingOrder.setUserPrinter(userPrinter);
				shippingOrderService.updateSelectiveById(shippingOrder);
			}
			
			//===条形码start
			Barcode128 code128 = new Barcode128();
			code128.setCode(shippingOrder.getShippingNo());
			Image image128 = code128.createImageWithBarcode(cd, null, null);
			image128.setAlignment(Image.MIDDLE);
			image128.scalePercent(170);
			Paragraph imgParagraph = new Paragraph();
			imgParagraph.add(image128);
			document.add(imgParagraph);
			//===条形码end
			
			//===地址start
			Paragraph addressParagraph = null;
			//控制手机显示，通通加密
			if(!roles.contains("telephone") || true) {
				String tel = shippingOrder.getTelephone();
				if(StringUtil.isNotBlank(tel)) {
					shippingOrder.setTelephone(tel.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
				}
			}
			if(ifcombination) {
				addressParagraph = new Paragraph("姓名：" + shippingOrder.getReceiver() + "   电话：" + shippingOrder.getTelephone()+"(组合商品,打包留意)", FontChinese_18);
			} else {
				addressParagraph = new Paragraph("姓名：" + shippingOrder.getReceiver() + "   电话：" + shippingOrder.getTelephone(), FontChinese_18);
			}
			addressParagraph.setLeading(22);
			addressParagraph.setSpacingBefore(5);
			document.add(addressParagraph);
			//===地址end
			
			//===包裹明细
			Paragraph detailParagraph = new Paragraph(shoppingDetail, FontChinese_15);
			detailParagraph.setLeading(12);
			detailParagraph.setSpacingBefore(5);
			if (shippingOrder.getLogisticCompany().equals("海淘一号仓") || shippingOrder.getLogisticCompany().equals("4PX")) {
				document.add(detailParagraph);
			}
			
			//===虚线start
			document.add(lineParagraph);
			//===虚线end
			
			//===快递公司:渠道start
			String logisticCompanyStr = "";
			String warehouseName = "";
			if(shippingOrder.getLogisticCompany()!=null && !shippingOrder.getLogisticCompany().equals("海带宝")) logisticCompanyStr += shippingOrder.getLogisticCompany();
			if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海带宝")) logisticCompanyStr += shippingOrder.getLogisticCompany()+"(SBJZR)";
			if(shippingOrder.getWarehouseName()!=null) warehouseName += shippingOrder.getWarehouseName();
			if(shippingOrder.getType()!=null && "LA".equals(shippingOrder.getWarehouseName()) && ifneedpackage && !shippingOrder.getLogisticCompany().equals("海淘一号仓")){
				logisticCompanyStr  += "\r\n("+warehouseName+"需打包"+")\r\n( "+ ShippingOrderType.of(shippingOrder.getType()).getDescription() + ")";
			} else if(shippingOrder.getLogisticCompany()!=null && shippingOrder.getLogisticCompany().equals("海淘一号仓")) {
				logisticCompanyStr  +=  "\r\n("+shippingOrder.getLogisticNo()+")\r\n( "+ ShippingOrderType.of(shippingOrder.getType()).getDescription() + ")";
				
			} else{
				logisticCompanyStr  += "\r\n("+warehouseName+")\r\n( "+ ShippingOrderType.of(shippingOrder.getType()).getDescription() + ")";
			}
			Paragraph logisticCompanyParagraph = new Paragraph(logisticCompanyStr, FontChinese_36);
			logisticCompanyParagraph.setLeading(42);
			logisticCompanyParagraph.setAlignment(Paragraph.ALIGN_CENTER);
			document.add(logisticCompanyParagraph);
			//===快递公司:渠道end
			
			//===添加商品start
			/*
			PdfPTable itemTable = new PdfPTable(tableWidths);
			itemTable.setSpacingBefore(0);
			itemTable.setSpacingAfter(0);
			itemTable.setWidthPercentage(100);
			itemTable.getDefaultCell().setFixedHeight(15);
			itemTable.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
			itemTable.getDefaultCell().setPadding(0);
			itemTable.addCell(new Phrase("货物信息", FontChinese_10));
			itemTable.addCell(new Phrase("UPC", FontChinese_10));
			itemTable.addCell(new Phrase("数量", FontChinese_10));
			List<Long> erpOrderIdList = HaiJsonUtils.toBean(shippingOrder.getErpOrderId(), new TypeReference<List<Long>>(){});
			List<ErpOrder> erpOrderList = erpOrderService.selectBatchIds(erpOrderIdList);
			for(int j=0; j<erpOrderList.size(); j++) {
				if(j == 6) {	//最多6个商品,第7个商品直接跳出
					Paragraph para = new Paragraph("•••••••••", FontChinese_10);
			        para.setAlignment(1);
			        para.setLeading(6);
					PdfPCell cell = new PdfPCell();
					cell.setColspan(3);
					cell.setBorder(PdfPCell.NO_BORDER);
					cell.addElement(para);
					itemTable.addCell(cell);
					break;
				}
				ErpOrder erpOrder = erpOrderList.get(j);
				String itemName = erpOrder.getItemName();
	    		itemName = itemName.replace("直邮", "");
	    		itemName = itemName.replace("拼邮", "");
	    		itemName = itemName.replace("包税", "");
				itemTable.addCell(new Phrase(itemName, FontChinese_10));
				itemTable.addCell(new Phrase(erpOrder.getUpc(), FontEnglish_8));
				itemTable.addCell(new Phrase(erpOrder.getQuantity().toString(), FontEnglish_8));
			}
			document.add(itemTable);
			*/
			//===添加商品end
			
			if(i<shippingOrderListLength-1) {
				document.newPage();
			}
		}
		document.close();
        writer.close();
        
        ResponseEntity<byte[]> filebyte = null;
        HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    	String fileName = "BarcodeList.pdf";
        headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"), "ISO8859-1"));
        filebyte = new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.OK);
        out.close();
        return filebyte; 
	}
	
	//包裹明细导出
	@RequestMapping("/shippingOrderExportExcel")
	@ResponseBody
	public ResponseEntity<byte[]> shippingOrderExportExcel(ShippingOrderQueryVO shippingOrderQueryVO) throws Exception {
		if(shippingOrderQueryVO.getStartOrderTime()==null || shippingOrderQueryVO.getEndOrderTime()==null) {
			throw new ErpCommonException("必须选择发货时间段");
		}
		ShiroUser shiroUser = this.getShiroUser();
		Set<String> roles = shiroUser.getRoles();

		String startOrderTimeStr = DateUtil.ymdFormat(shippingOrderQueryVO.getStartOrderTime());
		Date startOrderTime = DateUtil.parseDate(startOrderTimeStr + " 00:00:00");
		shippingOrderQueryVO.setStartOrderTime(startOrderTime);
		String endOrderTimeStr = DateUtil.ymdFormat(shippingOrderQueryVO.getEndOrderTime());
		Date endOrderTime = DateUtil.parseDate(endOrderTimeStr + " 23:59:59");
		shippingOrderQueryVO.setEndOrderTime(endOrderTime);
		List<List<Object>> rowDatas = new ArrayList<>();
		List<ErpOrder> erpOrderlist = shippingOrderService.queryByShippingOrderTime(shippingOrderQueryVO);
		if(erpOrderlist != null) {
			for (ErpOrder erpOrder : erpOrderlist) {
				List<Object> list = new ArrayList<>();
				
				list.add(erpOrder.getSkuCode());	//SKU编号
				list.add(erpOrder.getItemName());	//商品名称
				//sku图片
    			String skuPic = erpOrder.getSkuPic();
    			if(StringUtil.isNotBlank(skuPic)) {
    				PicModel pm = HaiJsonUtils.toBean(skuPic, PicModel.class);
        			String imgSrc = pm.getPicList().get(0).getUrl();
        			if(StringUtil.isNotBlank(imgSrc)) {
            			String imgType = imgSrc.substring(imgSrc.lastIndexOf(".") + 1).toUpperCase();
            			if(imgSrc.contains("aliyuncs.com")) {
            				imgSrc += "?x-oss-process=image/resize,m_lfit,h_100,w_100";
            			} else {
            				imgSrc = imgSrc.replaceAll("Resource", "Thumbnail");
            			}
            			//System.out.println(imgSrc);
            			URL url = new URL(imgSrc);
            			BufferedImage image = ImageIO.read(url);
            			ByteArrayOutputStream output = new ByteArrayOutputStream();
            	        ImageIO.write(image, imgType, output);
            	        output.flush();
            	        list.add(output.toByteArray());
            	        output.close();
        			} else {
        				list.add(null);
        			}
    			} else {
    				list.add(null);
    			}
    			list.add(erpOrder.getColor());				//商品颜色
    			list.add(erpOrder.getScale());				//商品尺码
    			list.add(erpOrder.getBrand());				//商品品牌
    			list.add(erpOrder.getUpc());				//商品条码
    			list.add(erpOrder.getQuantity());			//发货数量
    			//list.add(erpOrder.getSalePrice());			//商品单价
    			list.add(erpOrder.getGmtCreate());			//发货时间
    			list.add(erpOrder.getSalesName());			//销售员
    			list.add(erpOrder.getTargetNo());			//外部订单号
    			list.add(erpOrder.getErpNo());				//子订单编号
    			list.add(erpOrder.getNickName());			//小程序客户
    			list.add(erpOrder.getReceiver());			//收件人
				//收件人电话
				if(!roles.contains("telephone")) {
					String tel = erpOrder.getTelephone();
					if(StringUtil.isNotBlank(tel)) {
						list.add(tel.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
					}
				} else {
					list.add(erpOrder.getTelephone());
				}
    			list.add(erpOrder.getReceiverState());		//省
    			list.add(erpOrder.getReceiverCity());		//市
    			list.add(erpOrder.getReceiverDistrict());	//区
    			list.add(erpOrder.getAddressDetail());		//详细地址
    			list.add(erpOrder.getWarehouseName());		//仓库名称
    			list.add(erpOrder.getShippingNo());			//包裹号
    			list.add(erpOrder.getLogisticCompany());	//物流公司
    			list.add(ShippingOrderType.of(erpOrder.getType()).getDescription());//渠道方式
    			list.add(erpOrder.getLogisticNo());			//物流单号
    			if(erpOrder.getLogisticType()==null ||  erpOrder.getLogisticType()==0) {
    				list.add("直邮");
    			} else {
    				list.add("拼邮");
    			}
    			rowDatas.add(list);
			}
		}
		ExcelHelper excelHelper = new ExcelHelper();
    	String[] columnTitles = new String[]{"SKU编号", "商品名称", "商品图片", "颜色", "尺码", "品牌", "商品条码", "发货数量", "发货时间", "销售员","外部订单号","子订单编号","小程序客户","收件人", "手机", "省", "市", "区", "详细地址", "仓库", "包裹号", "物流公司","渠道方式", "物流单号", "发货方式"};
    	Integer[] columnWidth = new Integer[]{25, 25, 15, 20, 20, 20, 20, 20, 20, 20,25,25,20, 20, 20, 20, 20, 20, 20, 20, 25, 20, 20, 20, 20};
		
    	excelHelper.setShippingOrderToSheet("Shipping Order", columnTitles, rowDatas, columnWidth);
    	//excelHelper.writeToFile("/Users/liuyang/Work/test.xls");
    	
    	ResponseEntity<byte[]> filebyte = null;
    	ByteArrayOutputStream  out = excelHelper.writeToByteArrayOutputStream();
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    	String fileName = "订单发货明细表(" + DateUtil.formatDate(startOrderTime, "yyyyMMdd") + ").xlsx";
        headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"), "ISO8859-1"));
        
        filebyte = new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.OK);
        out.close();
        excelHelper.close();
        return filebyte; 
	}
	
	@RequestMapping("/shippingOrderPackageExportExcel")
	@ResponseBody
	public ResponseEntity<byte[]> shippingOrderPackageExportExcel(ShippingOrderQueryVO shippingOrderQueryVO) throws Exception {
		ShiroUser one = this.getShiroUser();
		Set<String> roles = one.getRoles();
		if(shippingOrderQueryVO.getStartOrderTime()==null && shippingOrderQueryVO.getStartActionTime()==null && shippingOrderQueryVO.getStatus()==null) {
			throw new ErpCommonException("必须选择查询时间段");
		}
		if(shippingOrderQueryVO.getStartOrderTime() != null) {
			String startOrderTimeStr = DateUtil.ymdFormat(shippingOrderQueryVO.getStartOrderTime());
			Date startOrderTime = DateUtil.parseDate(startOrderTimeStr + " 00:00:00");
			shippingOrderQueryVO.setStartOrderTime(startOrderTime);
		}
		if(shippingOrderQueryVO.getEndOrderTime() != null) {
			String endOrderTimeStr = DateUtil.ymdFormat(shippingOrderQueryVO.getEndOrderTime());
			Date endOrderTime = DateUtil.parseDate(endOrderTimeStr + " 23:59:59");
			shippingOrderQueryVO.setEndOrderTime(endOrderTime);
		}
		if(shippingOrderQueryVO.getStartActionTime() != null) {
			String startActionTimeStr = DateUtil.ymdFormat(shippingOrderQueryVO.getStartActionTime());
			Date startActionTime = DateUtil.parseDate(startActionTimeStr + " 00:00:00");
			shippingOrderQueryVO.setStartActionTime(startActionTime);
		}
		if(shippingOrderQueryVO.getEndActionTime() != null) {
			String endActionTimeStr = DateUtil.ymdFormat(shippingOrderQueryVO.getEndActionTime());
			Date endActionTime = DateUtil.parseDate(endActionTimeStr + " 23:59:59");
			shippingOrderQueryVO.setEndActionTime(endActionTime);
		}
		if(shippingOrderQueryVO.getStatus() != null) {
			shippingOrderQueryVO.setStatus(shippingOrderQueryVO.getStatus());
		}
		shippingOrderQueryVO.setCompanyId(one.getCompanyId());
		List<List<Object>> rowDatas = new ArrayList<>();
		List<ShippingOrder> shippingOrderList = shippingOrderService.queryByShippingOrderPackageTime(shippingOrderQueryVO);
		
		if(shippingOrderList != null) {
			for (ShippingOrder shippingOrder : shippingOrderList) {
				List<Object> list = new ArrayList<>();
				list.add(shippingOrder.getShippingNo());
				list.add(shippingOrder.getLogisticCompany());
				list.add(shippingOrder.getActionTime());
				list.add(shippingOrder.getFreight());
				list.add(shippingOrder.getSkuWeight());
				list.add(shippingOrder.getReceiver());
				list.add(shippingOrder.getReceiverState());
				list.add(shippingOrder.getReceiverCity());
				list.add(shippingOrder.getReceiverDistrict());
				list.add(shippingOrder.getAddressDetail());
				//收件人电话
				if(!roles.contains("telephone")) {
					String tel = shippingOrder.getTelephone();
					if(StringUtil.isNotBlank(tel)) {
						list.add(tel.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
					}
				} else {
					list.add(shippingOrder.getTelephone());
				}
				list.add(shippingOrder.getIdCard());
				String erpOrder = shippingOrder.getErpOrderId();
				List<Long> erpOrderIdList = HaiJsonUtils.toBean(erpOrder, new TypeReference<List<Long>>(){});
				String shippingDetai = "";
				if(CollectionUtils.isNotEmpty(erpOrderIdList)) {
					List<ErpOrder> erpOrders = erpOrderMapper.queryErpOrderDetailByIds(erpOrderIdList);
					for (ErpOrder erpOrder2 : erpOrders) {
						shippingDetai += ","+erpOrder2.getItemName()+erpOrder2.getBrand()+"-Color:"+erpOrder2.getColor()+",Size:"+erpOrder2.getScale()+"*"+erpOrder2.getQuantity();
					}
				 }
				list.add(shippingDetai);
				list.add(shippingOrder.getUserCreate());
				list.add(shippingOrder.getGmtCreate());
    			rowDatas.add(list);
			}
		}
		ExcelHelper excelHelper = new ExcelHelper();
    	String[] columnTitles = new String[]{"包裹单号", "物流公司", "库内操作时间", "预估物流费用", "商品净重(磅)", "收货人", "省", "市", "区", "详细地址", "联系电话", "身份证","包裹明细","创建者","创建时间"};
    	Integer[] columnWidth = new Integer[]{25, 25, 25, 15, 20, 20, 20, 20, 20, 25, 20, 25, 35, 20, 20};
    	excelHelper.setShippingOrderPackageToSheet("Shipping Order Detail", columnTitles, rowDatas, columnWidth);
    	//excelHelper.writeToFile("/Users/liuyang/Work/test.xls");
    	
    	ResponseEntity<byte[]> filebyte = null;
    	ByteArrayOutputStream  out = excelHelper.writeToByteArrayOutputStream();
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    	String fileName = "包裹明细(" + DateUtil.formatDate(new Date(), "yyyyMMdd") + ").xlsx";
        headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"), "ISO8859-1"));
        
        filebyte = new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.OK);
        out.close();
        excelHelper.close();
        return filebyte; 
	}
	
	//预出库
	@RequestMapping("/prepareShipping")
	@ResponseBody
	public Object prepareShipping(String erpOrderId) {
		String s = erpOrderId.replace("&quot;", "\"");
		List<Long> erpOrderIdList = HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
		List<ErpOrder> erpOrderList = erpOrderService.selectBatchIds(erpOrderIdList);
		StringBuffer errorMsg = new StringBuffer();
		erpOrderList.forEach(erpOrder -> {
			//拼邮、备货状态(已备货)、子订单状态(新建)
			if(erpOrder.getLogisticType()!=null && erpOrder.getLogisticType() !=0 && erpOrder.getStockStatus()==StockUpStatus.STOCKUP.getCode() && erpOrder.getStatus()==OrderStatus.INIT.getCode()) {
				erpOrder.setStockStatus(StockUpStatus.PREPARE.getCode());
				erpOrderService.updateSelectiveById(erpOrder);
			} else {
				errorMsg.append(erpOrder.getErpNo() + ",");
			}
		});
		
		String errorMsgStr = errorMsg.toString();
		if(StringUtil.isNotBlank(errorMsgStr)) {
			errorMsgStr = "子订单号：" + errorMsgStr + "状态有误，只有拼邮、备货状态(已备货)、子订单状态(新建)的子订单才能预出库";
			return JsonResult.buildFailed(errorMsgStr);
		} else {
			return JsonResult.buildSuccess(null);
		}
	}
	
	/**
	 * 标记是否对账 
	 */
	@RequestMapping("/checkFileIsPay")
	@ResponseBody
	public Object checkFileIsPay(String fileUrl,String remark) throws Exception {
		JsonResult<Object> result = new JsonResult<>();
		List<List<Object>> allRows = AnalysisExcelUtil.analysisExcel(fileUrl);
		
		List<ShippingOrder> shippingOrderList = new ArrayList<ShippingOrder>();
		for (int i = 0; i < allRows.size(); i++) {
			List<Object> rowDataTemp = allRows.get(i);
			ShippingOrder shippingOrder = new ShippingOrder();
			if(StringUtil.isBlank(rowDataTemp.get(0).toString()) || StringUtil.isBlank(rowDataTemp.get(1).toString())) {
				continue;
			}
			shippingOrder.setShippingNo(rowDataTemp.get(0).toString());
			shippingOrder.setLogisticCompany(rowDataTemp.get(1).toString());
			
			shippingOrder.setIsPay(1);
			shippingOrder.setPayRemark(remark);
			if(rowDataTemp.size()>2 && StringUtil.isNotBlank(rowDataTemp.get(2).toString())) {
				shippingOrder.setThirdWeight(Double.valueOf(rowDataTemp.get(2).toString()));
			}
			if(rowDataTemp.size()>3 && StringUtil.isNotBlank(rowDataTemp.get(3).toString())) {
				shippingOrder.setThirdPostage(Double.valueOf(rowDataTemp.get(3).toString()));
			}
			shippingOrderList.add(shippingOrder);
		}
		if(shippingOrderList.size() > 0) {
			shippingOrderMapper.updateIsPayByShippingOrders(shippingOrderList);
		}
		return result.buildIsSuccess(true);
	}

	/**
	 * 核对错误PKG 
	 */
	@RequestMapping("/checkErrorPkg")
	@ResponseBody
	public ResponseEntity<byte[]> checkErrorPkg(String fileUrl) throws Exception {
		List<List<Object>> allRows = AnalysisExcelUtil.analysisExcel(fileUrl);
		List<ShippingOrder> shippingOrderList = new ArrayList<ShippingOrder>();
		for (int i = 0; i < allRows.size(); i++) {
			List<Object> rowDataTemp = allRows.get(i);
			EntityWrapper<ShippingOrder> entityWrapper = new EntityWrapper<>();
			entityWrapper.where("shipping_no={0}", rowDataTemp.get(0).toString());
			entityWrapper.and("logistic_company={0} and is_pay=0", rowDataTemp.get(1).toString());
			entityWrapper.notIn("status", "-1,4");
			ShippingOrder shippingOrder = shippingOrderService.selectOne(entityWrapper);
			if(shippingOrder == null) {
				ShippingOrder shippingOrderTemp = new ShippingOrder();
				shippingOrderTemp.setShippingNo(rowDataTemp.get(0).toString());
				shippingOrderTemp.setLogisticCompany(rowDataTemp.get(1).toString());
				shippingOrderTemp.setExportReason("包裹物流不对");
				shippingOrderList.add(shippingOrderTemp);
			} else if (rowDataTemp.get(2).toString().equals("4")) {
				boolean ifAbove = true;
				EntityWrapper<ShippingOrder> entityWrapperOne = new EntityWrapper<>();
				entityWrapperOne.where("shipping_no={0}", rowDataTemp.get(0).toString());
				ShippingOrder shippingOrderOne = shippingOrderService.selectOne(entityWrapper);
				List<ErpOrder> ErpOrderList = shippingOrderService.queryShippingOrderDetail(shippingOrderOne.getErpOrderId());
				Map<String, String> categorymap = MapUtil.luxuItem();
				Map<String, String> categorymapLuxu = MapUtil.getCategoryLuxu();
				for (ErpOrder erpOrder : ErpOrderList) {
					for (Map.Entry<String, String> entry : categorymap.entrySet()) {
						if (erpOrder.getBrand().contains(entry.getKey())) {
							ifAbove = false;
						}
					}
					for (Map.Entry<String, String> entry : categorymapLuxu.entrySet()) {
						if (erpOrder.getCategoryName().equals(entry.getKey())) {
							ifAbove = false;
						}
					}
				}
				if(ifAbove) {
					ShippingOrder shippingOrderTemp = new ShippingOrder();
					shippingOrderTemp.setShippingNo(rowDataTemp.get(0).toString());
					shippingOrderTemp.setLogisticCompany(rowDataTemp.get(1).toString());
					shippingOrderTemp.setExportReason("收费归档不对");
					shippingOrderList.add(shippingOrderTemp);
				}
			}

		}
		ResponseEntity<byte[]> notPayPkg = isNotPayPkg(shippingOrderList);
		return notPayPkg;
	}

	/**
	 * 导出未支付的PKG
	 */
	public ResponseEntity<byte[]> isNotPayPkg(List<ShippingOrder> shippingOrderList) throws Exception{
		List<List<Object>> rowDatas = new ArrayList<>();
		if(shippingOrderList != null) {
			for (ShippingOrder shippingOrder : shippingOrderList) {
				List<Object> list = new ArrayList<>();
				list.add(shippingOrder.getShippingNo());
				list.add(shippingOrder.getLogisticCompany());
				list.add(shippingOrder.getExportReason());
				rowDatas.add(list);
			}
		}
		ExcelHelper excelHelper = new ExcelHelper();
    	String[] columnTitles = new String[]{"包裹单号", "物流公司","校验原因"};
    	Integer[] columnWidth = new Integer[]{25, 25, 25};
    	excelHelper.setShippingOrderPkgToSheet("Shipping Order Check", columnTitles, rowDatas, columnWidth);
    	//excelHelper.writeToFile("/Users/liuyang/Work/test.xls");

    	ResponseEntity<byte[]> filebyte = null;
    	ByteArrayOutputStream  out = excelHelper.writeToByteArrayOutputStream();
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    	String fileName = "核对完毕返回错误的包裹号和已支付的包裹号.xlsx";
        headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"), "ISO8859-1"));

        filebyte = new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.OK);
        out.close();
        excelHelper.close();;
        return filebyte;
	}

	/**
	 * 查看发货单明细
	 */
	@RequestMapping("/queryShippingOrderDetail")
	@ResponseBody
	public Object queryShippingOrderDetail(Long shippingOrderId) {
		JsonPageResult<List<ErpOrder>> result = new JsonPageResult<>();
		try{
			ShippingOrder shippingOrder = shippingOrderService.selectById(shippingOrderId);
			String erpOrderIds = shippingOrder.getErpOrderId();
			List<ErpOrder> ErpOrderList = shippingOrderService.queryShippingOrderDetail(erpOrderIds);
			for (ErpOrder erpOrder : ErpOrderList) {
				erpOrder.setType(shippingOrder.getType());
			}
			result.setData(ErpOrderList);
			return result.buildIsSuccess(true);
		} catch(ErpCommonException e) {
			return result.buildIsSuccess(false).buildMsg(e.getErrorMsg());
		} catch(Exception ex) {
			return result.buildIsSuccess(false).buildMsg("未知异常");
		}
	}
	
	/**
	 * 运通接口测试
	 * @param id
	 * @return
	 */
  	@RequestMapping("/yuntongTest")
  	public void queryLogisticCompany(Long id) {
  		yunTongService.createOrder(4800l);
  	}

	/**
	 * 邮客接口测试
	 */
	@RequestMapping("/youkeTest")
	public void youkeTest() {
		//youkeService.createOrder(2l);
		//youkeService.inboundStatus("PKG17062502002910007");
		//youkeService.orderStatus("1739255020");
		EntityWrapper<ShippingOrder> entityWrapper = new EntityWrapper<>();
		entityWrapper.where("shipping_no = {0} ", "PKG17062710132810022");
		ShippingOrder Order = shippingOrderService.selectOne(entityWrapper);
		haihuService.returnPackageNo(Order.getId());
	}

	/**
	 * 批量订正主订单状态
	 */
	@RequestMapping("/updateOuterstatusBatch")
	public void updateOuterstatusBatch() {
		EntityWrapper<OuterOrder> entityWrapper = new EntityWrapper<>();
		entityWrapper.where("status={0}", 0);
		List<OuterOrder> outerOrderList = outerOrderService.selectList(entityWrapper);
		Set<Long> mainIds = Sets.newHashSet();
		for(int i=0; i<outerOrderList.size(); i++) {
			mainIds.add(outerOrderList.get(i).getId());
		}
		System.out.println(mainIds.size());
		shippingOrderService.updateOuterstatus(mainIds);
	}
	
	/**
	 * 判断一个人一周内发货包裹数
	 */
	@RequestMapping("/checkManyTimesDelivery")
	@ResponseBody
	public Object checkManyTimesDelivery(String idCard, String logisticCompany, String erpOrderIds, boolean isBatch) {
	    if(StringUtil.isNotBlank(idCard) && StringUtil.isNotBlank(logisticCompany) && !isBatch) {
	    	if("4PX".equals(logisticCompany) && StringUtil.isNotBlank(erpOrderIds)) {
	    		String s = erpOrderIds.replace("&quot;", "\"");
				List<Long> erpOrderIdList = HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
				List<ErpOrder> erpOrderList = erpOrderService.selectBatchIds(erpOrderIdList);
				Double price = 0.00;
				for(int i=0; i<erpOrderList.size(); i++) {
					ErpOrder erpOrder = erpOrderList.get(i);
					price += erpOrder.getSalePrice();
				}
				if(price >= 1000) {
					return JsonResult.buildFailed("注意：4PX商品总价不能超过1000元，请更换其他物流公司。");
				}
	    	}
			EntityWrapper<ShippingOrder> entityWrapper = new EntityWrapper<ShippingOrder>();
			entityWrapper.where("id_card={0} and logistic_company={1} and gmt_create>=DATE_SUB(CURDATE(), INTERVAL 6 DAY)", idCard, logisticCompany);
			int num = shippingOrderService.selectCount(entityWrapper);
			if(num >= 2 && logisticCompany.equals("邮客")) {
				return JsonResult.buildFailed("注意：此收件人已用\"" + logisticCompany + "\"在一周之内发过2次以上请更换其他物流公司了");
			} else if(num >= 5 && logisticCompany.equals("4PX")) {
				return JsonResult.buildFailed("注意：此收件人已用\"" + logisticCompany + "\"在一周之内发过5次以上请更换其他物流公司了");
			} else {
				return JsonResult.buildSuccess(null);
			}
		} else if(StringUtil.isNotBlank(erpOrderIds) && StringUtil.isNotBlank(logisticCompany) && isBatch) {
			String s = erpOrderIds.replace("&quot;", "\"");
			List<Long> erpOrderIdList = HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
			List<ErpOrder> erpOrderList = erpOrderService.selectBatchIds(erpOrderIdList);
			String error = "";
			for(int i=0; i<erpOrderList.size(); i++) {
				ErpOrder erpOrder = erpOrderList.get(i);
				if("4PX".equals(logisticCompany)) {
					Double price = erpOrderList.get(i).getSalePrice()*erpOrderList.get(i).getQuantity();
					if(price >= 1000) {
						return JsonResult.buildFailed("注意：4PX商品总价不能超过1000元，请更换其他物流公司," + erpOrderList.get(i).getErpNo());
					}
		    	}
				String idCardTemp = erpOrder.getIdCard();
				if(StringUtil.isNotBlank(idCardTemp)) {
					EntityWrapper<ShippingOrder> entityWrapper = new EntityWrapper<ShippingOrder>();
					entityWrapper.where("id_card={0} and logistic_company={1} and gmt_create>=DATE_SUB(CURDATE(), INTERVAL 6 DAY)", idCardTemp, logisticCompany);
					int num = shippingOrderService.selectCount(entityWrapper);
					if(num >= 2) {
						error += erpOrder.getReceiver() + "，";
					}
				}
			}
			if(StringUtil.isNotBlank(error)) {
				return JsonResult.buildFailed("注意：" + error + "用\"" + logisticCompany + "\"在一周之内发货2次以上请更换其他物流公司了");
			} else {
				return JsonResult.buildSuccess(null);
			}
		}
		return JsonResult.buildSuccess(null);
	}
	
	/**
	 * 邮客接口测试
	 * @throws ParseException 
	 */
	@RequestMapping("/FadroadTest")
	public void FadRoadTest(String packageNO) throws ParseException {
		//fadRoadService.shippingTrack(packageNO);
	    siFangService.shippingTrack(packageNO);
	}
	/**
	 * 完整物流轨迹详情展示
	 * @param shippingNo
	 * @return
	 */
	@RequestMapping("/getShippingTrackDetail")
	@ResponseBody
	public Object getShippingTrackDetail(String shippingNo) {
		JsonResult<Object> result = new JsonResult<Object>();
		if (StringUtils.isNotBlank(shippingNo)) {
			List<ShippingTrack> shippingTracks = shippingTrackMapper.queryShippingTrack(shippingNo);
			List<ShippingTrackVO> shippingTrackVOList = Lists.newArrayList();
			if (shippingTracks.size() > 0) {
				shippingTracks.forEach(shippingTrack -> {
					ShippingTrackVO shippingOne = new ShippingTrackVO();
					switch (shippingTrack.getStatus()) {
					case 0:
						shippingOne.setGmtCreate(shippingTrack.getGmtModify());
						shippingOne.setInfo("未出库");
						shippingTrackVOList.add(shippingOne);
						break;
					case 1:
						shippingOne.setGmtCreate(shippingTrack.getOverseaOutTime());
						shippingOne.setInfo("已出库");
						shippingTrackVOList.add(shippingOne);
						break;
					case 2:
						shippingOne.setGmtCreate(shippingTrack.getOverseaOnTransferTime());
						shippingOne.setInfo("递交航空公司");
						shippingTrackVOList.add(shippingOne);
						break;	
					case 3:
						if(shippingTrack.getInlandInTime()!= null){
							shippingOne.setGmtCreate(shippingTrack.getInlandInTime());
						}else{
							shippingOne.setGmtCreate(shippingTrack.getGmtCreate());
						}
						shippingOne.setInfo("清关");
						shippingTrackVOList.add(shippingOne);
						break;
					case 4:
						if(shippingTrack.getInlandOutTime()!=null) {
							shippingOne.setGmtCreate(shippingTrack.getInlandOutTime());
						} else {
							shippingOne.setGmtCreate(shippingTrack.getGmtCreate());
						}
						shippingOne.setInfo("国内派送");
						shippingTrackVOList.add(shippingOne);
						String infodetail = "";
						JSONArray jsonArrayss = null;
						for (int i = 0; i < shippingTracks.size(); i++) {
							if (shippingTracks.get(i).getStatus() == 4) {
								infodetail = shippingTracks.get(i).getInfo();
								if (StringUtils.isNotBlank(infodetail) && !infodetail.equals("已转国内快递") && infodetail.contains("{")) {
									JSONObject object = JSONObject.fromObject(infodetail);
									if (shippingTrack.getInlandExpressId().equals("tiantian")
											|| shippingTrack.getInlandExpressId().equals("百世汇通")) {
										jsonArrayss = object.getJSONArray("data");
										for (int j = jsonArrayss.size() - 1; j > 0; j--) {
											ShippingTrackVO shippingTrackArray = new ShippingTrackVO();
											JSONObject object2 = jsonArrayss.getJSONObject(j);
											Date time = DateUtil.parseDate(object2.getString("time"));
											shippingTrackArray.setGmtCreate(time);
											shippingTrackArray.setInfo(String.valueOf(object2.get("context")));
											shippingTrackVOList.add(shippingTrackArray);
										}
									} else {
										if(object.containsKey("data")){
											jsonArrayss = object.getJSONArray("data");
											for (int j = jsonArrayss.size() - 1; j > 0; j--) {
												ShippingTrackVO shippingTrackArray = new ShippingTrackVO();
												JSONObject object2 = jsonArrayss.getJSONObject(j);
												Date time = DateUtil.parseDate(object2.getString("time"));
												shippingTrackArray.setGmtCreate(time);
												shippingTrackArray.setInfo(String.valueOf(object2.get("context")));
												shippingTrackVOList.add(shippingTrackArray);
											}
										}else{
											jsonArrayss = object.getJSONArray("Traces");
											for (int j = jsonArrayss.size() - 1; j > 0; j--) {
												ShippingTrackVO shippingTrackArray = new ShippingTrackVO();
												JSONObject object2 = jsonArrayss.getJSONObject(j);
												Date time = DateUtil.parseDate(object2.getString("AcceptTime"));
												shippingTrackArray.setGmtCreate(time);
												shippingTrackArray.setInfo(String.valueOf(object2.get("AcceptStation")));
												shippingTrackVOList.add(shippingTrackArray);
											}
										}
									}
								}

							}
						}
						break;
					case 5:
						shippingOne.setGmtCreate(shippingTrack.getGmtCreate());
						shippingOne.setInfo("签收");
						shippingTrackVOList.add(shippingOne);
						break;
					}
				});
			}
			ListSort(shippingTrackVOList);
			result.buildData(shippingTrackVOList).buildIsSuccess(true);
		} else {
			result.buildIsSuccess(false).buildMsg("包裹信息异常！");
		}
		return result;
	}
	/**
	 * 每日打包信息
	 */
	@RequestMapping("/markPackage")
	@ResponseBody
	public Object markPackage(String fileUrl) throws Exception {
		JsonResult<Object> result = new JsonResult<>();
		List<List<Object>> allRows = AnalysisExcelUtil.analysisExcel(fileUrl);
		for (int i = 0; i < allRows.size(); i++) {
			List<Object> rowDataTemp = allRows.get(i);
			shippingOrderMapper.updatePackage(rowDataTemp.get(0).toString(), rowDataTemp.get(1).toString());
		}
		String fileName = "每日每天打包表(" + DateUtil.formatDate(new Date(), "yyyyMMdd") + ").xlsx";
		String strJson = "{\"allFileList\":[{\"url\":\""+fileUrl+"\"}]}";  
		ShiroUser one = this.getShiroUser();
		FileManage fileManage = new FileManage();
		fileManage.setCompanyId(1L);
		fileManage.setCreateBy(one.getLoginName());
		fileManage.setFileName(fileName);
		fileManage.setFileUrl(strJson);
		fileManage.setGmtCreate(new Date());
		fileManage.setGmtModify(new Date());
		fileManage.setOrganizationId(7L);
		fileManage.setOrganizationName("采购部");
		fileManageService.insert(fileManage);
		return result.buildIsSuccess(true);
	}
	/***
	 * 增加追回包裹需求
	 * @param shippingOrderId
	 * @return
	 */
	@RequestMapping("/updatePackageStatusByid")
	@ResponseBody
	public Object updatePackageStatusByid(Long shippingOrderId,Integer status,String backReason){
		JsonResult<ShippingOrder> result = new JsonResult<>();
		if(shippingOrderId!=null && status != null){
			ShippingOrderQueryVO shippingOrderQueryVO = new ShippingOrderQueryVO();
			shippingOrderQueryVO.setShippingOrderId(shippingOrderId);
			shippingOrderQueryVO.setStatus(status);
			shippingOrderQueryVO.setBackReason(backReason);
			shippingOrderMapper.updatePackageStatusByid(shippingOrderQueryVO);
		}		
		return result.buildIsSuccess(true);
	}
	
	// 查询物流线路
	@RequestMapping("/queryLogisticType")
	@ResponseBody
	public Object queryLogisticType() {
		JsonResult<List<LogisticType>> result = new JsonResult<>();
		List<LogisticType> LogisticTypeList = shippingOrderService.queryLogisticType();
		result.setData(LogisticTypeList);
		result.setSuccess(true);
		return result;
	}
	// 恢复数据状态
    @RequestMapping("/rollbackShippingOrder")
	@ResponseBody
	public Object rollbackShippingOrder(Long shippingOrderId,String backReason) {
		JsonResult<List<ShippingOrder>> result = new JsonResult<>();
		ShippingOrder shippingOrder = shippingOrderService.selectById(shippingOrderId);
		List<InventoryRecord> listRecord = inventoryRecordMapper.rollBackInventoryArea(shippingOrderId);
		for (InventoryRecord inventoryRecord : listRecord) {
			InventoryArea inventoryArea = inventoryAreaMapper.selectById(inventoryRecord.getInventoryAreaId());
			EntityWrapper<Inventory> entityWrapper = new EntityWrapper<Inventory>();
			entityWrapper.where("sku_code={0}",inventoryArea.getSkuCode());
			Inventory inventory = inventoryService.selectOne(entityWrapper);
			inventory.setInventory(inventory.getInventory() + inventoryRecord.getQuantity());
			inventory.setLockedInv(inventory.getLockedInv() + inventoryRecord.getQuantity());
			inventoryArea.setInventory(inventoryArea.getInventory()+ inventoryRecord.getQuantity());
			inventoryArea.setLockedInv(inventoryArea.getLockedInv()+ inventoryRecord.getQuantity());
			inventoryAreaMapper.updateSelectiveById(inventoryArea);
			inventoryService.updateById(inventory);
			
		}
		List<InventoryInout> listInout = inventoryInoutMapper.queryInventoryInoutByshippingId(shippingOrderId);
		for (InventoryInout inventoryInout : listInout) {
			InventoryInout inoutOne = inventoryInoutMapper.selectById(inventoryInout.getId());
			inoutOne.setInoutReason("记录无效");
			inventoryInoutMapper.updateSelectiveById(inoutOne);
		}
		String erpOrderIds = shippingOrder.getErpOrderId();
		String s = erpOrderIds.replace("&quot;", "\"");
		List<Long> erpOrderIdList = HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
		List<ErpOrder> ErpOrderList = erpOrderMapper.queryByerpOrderIdForDetail(erpOrderIdList);
		for (ErpOrder erpOrder : ErpOrderList) {
			OuterOrderDetail  outerOne = outerOrderDetailMapper.selectById(erpOrder.getOuterDetailOrderId());
			erpOrder.setLogisticType(outerOne.getLogisticType());
			erpOrderMapper.updateSelectiveById(erpOrder);
		}
		erpOrderMapper.rollBackForErpOrder(shippingOrderId);
		shippingOrder.setMistake(backReason);
		shippingOrder.setStatus(ShippingOrderStatus.REVOCATIONOFSHIPMENTS.getCode());
		shippingOrderService.updateSelectiveById(shippingOrder);
		result.setSuccess(true);
		return result;
	}
    
    @RequestMapping("/doubleCheckById")
   	@ResponseBody
   	public Object doubleCheckById(ShippingOrder shippingorder) {
   		JsonResult<List<ShippingOrder>> result = new JsonResult<>();
   		if(shippingorder.getId() != null) {
   			ShippingOrder shippingOrder = shippingOrderService.selectById(shippingorder.getId());
   	   		shippingOrder.setThirdPostage(shippingorder.getThirdPostage());
   	   		shippingOrder.setShippingTax(shippingorder.getShippingTax());
   	   		shippingOrder.setCompensatePostage(shippingorder.getCompensatePostage());
   	   		shippingOrderService.updateSelectiveById(shippingOrder);
   			result.setSuccess(true);
   		} else {
   			result.buildIsSuccess(false).buildMsg("错误数据");
   		}
   		return result;
   		}
    
    
	private static void ListSort(List<ShippingTrackVO> list) {
		Collections.sort(list, new Comparator<ShippingTrackVO>() {
			@Override
			public int compare(ShippingTrackVO o1, ShippingTrackVO o2) {
				Date dt1 = o1.getGmtCreate();
				Date dt2 = o2.getGmtCreate();
				if (dt1.getTime() < dt2.getTime()) {
					return -1;
				} else if (dt1.getTime() > dt2.getTime()) {
					return 1;
				} else {
					return 0;
				}
			}
		});
	}
}

class CustomDashedLineSeparator extends DottedLineSeparator {
    protected float dash = 5;
    protected float phase = 2.5f;

    public float getDash() {
        return dash;
    }

    public float getPhase() {
        return phase;
    }

    public void setDash(float dash) {
        this.dash = dash;
    }

    public void setPhase(float phase) {
        this.phase = phase;
    }

    public void draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) {
    	canvas.saveState();
        canvas.setLineWidth(lineWidth);
        canvas.setLineDash(dash, gap, phase);
        drawLine(canvas, llx, urx, y);
        canvas.restoreState();
    }

    
    
    	


}